package DataServer

import (
	"fmt"
	"log"
	"os"
	"os/exec"
	"runtime"
	"strconv"
	"strings"

	"github.com/fatih/color"
)

type Bar struct {
	width   int
	PerLen  float32
	AllSize int64
	NowSize int64
	Running func(args ...interface{}) string
}

var SCREEN_HEIGHT int

func NewBar(allCount int64) (bar *Bar) {
	bar = new(Bar)
	bar.Running = color.New(color.Bold, color.BgGreen).SprintFunc()

	if runtime.GOOS != "windows" {
		cmd := exec.Command("stty", "size")
		cmd.Stdin = os.Stdin
		out, err := cmd.Output()
		if err != nil {
			log.Fatal(err)
		}
		bar.width, err = strconv.Atoi(strings.Fields(string(out))[1])
		SCREEN_HEIGHT, err = strconv.Atoi(strings.Fields(string(out))[0])
		bar.width -= 10
		bar.PerLen = float32(bar.width) / float32(100.0)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		bar.width = 20
		bar.PerLen = float32(bar.width) / float32(100.0)
	}
	bar.AllSize = allCount
	return bar
}

func (bar *Bar) Increment(p int64) {
	bar.NowSize += p
	if bar.NowSize == bar.AllSize {
		fmt.Print("\r\033[1B")
	}
}

func (bar *Bar) Log(args ...interface{}) {
	percent := bar.NowSize * 100 / bar.AllSize
	raw := fmt.Sprint(args...)
	pro := int(bar.PerLen * float32(percent))
	if len(raw) < pro {
		for {
			if len(raw) < pro {
				raw += " "
			} else {
				break
			}
		}
		fmt.Print("\r", "(", percent, "%)", bar.Running(raw))
	} else {
		preStr := raw[:pro]
		fmt.Print("\r", "(", percent, "%)", bar.Running(preStr), raw[pro:])
	}
	if percent == 100 {
		fmt.Println()
	}
}

func (bar *Bar) Println(args ...interface{}) {
	// s := "\33[2K\r"
	// args = append([]interface{}{}, args...)

	fmt.Println(args...)
}
